package com.coder.algorithm.leetcode

/**
 * [541. 反转字符串 II](https://leetcode-cn.com/problems/reverse-string-ii/)
 *
 * @author yuhus
 * @date: 2022/3/28
 */
object l_0541 {
    fun reverseStr(s: String, k: Int): String {
        var charArray = s.toCharArray()
        var l = 0
        while (l < s.length) {
            if (l + k < s.length) {
                reverseWords(charArray, l, l + k - 1)
            } else {
                reverseWords(charArray, l, s.length - 1)
            }
            l += k * 2
        }
        return String(charArray)
    }

    private fun reverseWords(charArray: CharArray, l: Int, r: Int) {
        var start = l
        var end = r
        var temp: Char
        while (start < end) {
            temp = charArray[start]
            charArray[start] = charArray[end]
            charArray[end] = temp
            start++
            end--
        }
    }
}